package org.example.config;

import org.example.handler.ReceiverMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * MQTT 消息入站配置
 *
 * @author Brant
 * @since 2025-04-21
 */
@Configuration
public class MqttInboundConfiguration {
    /**
     * 注入配置类
     */
    @Autowired
    private MqttPropertiesConfig mqttPropertiesConfig;
    /**
     * 注入 MQTT 客户端工厂
     */
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;
    /**
     * 注入消息处理器
     */
    @Autowired
    private ReceiverMessageHandler receiverMessageHandler;

    /**
     * 消息通道
     *
     * @return 消息通道
     */
    @Bean
    public MessageChannel messageInboundChannel() {
        return new DirectChannel();
    }

    /**
     * 配置入站适配器
     * 作用： 设置订阅主题，以及指定消息的通道 等相关属性
     *
     * @return 消息生产者
     */
    @Bean
    public MessageProducer messageProducer() {
        MqttPahoMessageDrivenChannelAdapter channelAdapter = new MqttPahoMessageDrivenChannelAdapter(
            mqttPropertiesConfig.getUrl(),
            mqttPropertiesConfig.getSubClientId(),
            mqttPahoClientFactory,
            mqttPropertiesConfig.getSubTopic().split(",")
        );
        channelAdapter.setQos(1);
        channelAdapter.setConverter(new DefaultPahoMessageConverter());
        channelAdapter.setOutputChannel(messageInboundChannel());
        return channelAdapter;
    }

    /**
     * 指定处理消息来自哪个通道
     */
    @Bean
    @ServiceActivator(inputChannel = "messageInboundChannel")
    public MessageHandler messageHandler() {
        return receiverMessageHandler;
    }
}